import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/fishing_report_provider.dart';
import '../../models/fishing_report.dart';

class FishingReportPage extends StatefulWidget {
  const FishingReportPage({super.key});

  @override
  State<FishingReportPage> createState() => _FishingReportPageState();
}

class _FishingReportPageState extends State<FishingReportPage>
    with TickerProviderStateMixin {
  late TabController _tabController;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    
    // 监听滚动事件，实现上拉加载更多
    _scrollController.addListener(_onScroll);
    
    // 初始化数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final provider = context.read<FishingReportProvider>();
      provider.loadReports(refresh: true);
      provider.loadStats();
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      // 距离底部200像素时开始加载更多
      final provider = context.read<FishingReportProvider>();
      if (provider.hasMore && !provider.isLoadingMore) {
        provider.loadReports();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text('钓况报告'),
        backgroundColor: Colors.blue[600],
        foregroundColor: Colors.white,
        elevation: 0,
        bottom: TabBar(
          controller: _tabController,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white70,
          indicatorColor: Colors.white,
          tabs: const [
            Tab(text: '最新报告'),
            Tab(text: '数据统计'),
          ],
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.filter_list),
            onPressed: _showFilterDialog,
          ),
        ],
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildReportsTab(),
          _buildStatsTab(),
        ],
      ),
    );
  }

  Widget _buildReportsTab() {
    return Consumer<FishingReportProvider>(
      builder: (context, provider, child) {
        if (provider.isLoading && provider.reports.isEmpty) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        if (provider.error != null && provider.reports.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.error_outline,
                  size: 64,
                  color: Colors.grey[400],
                ),
                const SizedBox(height: 16),
                Text(
                  provider.error!,
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 16,
                  ),
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () => provider.loadReports(refresh: true),
                  child: const Text('重试'),
                ),
              ],
            ),
          );
        }

        if (provider.reports.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.assessment_outlined,
                  size: 64,
                  color: Colors.grey[400],
                ),
                const SizedBox(height: 16),
                Text(
                  '暂无钓况报告',
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 16,
                  ),
                ),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: () => provider.loadReports(refresh: true),
          child: ListView.builder(
            controller: _scrollController,
            padding: const EdgeInsets.all(16),
            itemCount: provider.reports.length + (provider.hasMore ? 1 : 0),
            itemBuilder: (context, index) {
              if (index == provider.reports.length) {
                // 加载更多指示器
                return Container(
                  padding: const EdgeInsets.all(16),
                  child: Center(
                    child: provider.isLoadingMore
                        ? const CircularProgressIndicator()
                        : const Text(
                            '没有更多数据了',
                            style: TextStyle(color: Colors.grey),
                          ),
                  ),
                );
              }

              final report = provider.reports[index];
              return _buildReportCard(report);
            },
          ),
        );
      },
    );
  }

  Widget _buildReportCard(FishingReport report) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 头部信息
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                CircleAvatar(
                  radius: 20,
                  backgroundImage: report.reporterAvatar.isNotEmpty
                      ? NetworkImage(report.reporterAvatar)
                      : null,
                  child: report.reporterAvatar.isEmpty
                      ? const Icon(Icons.person)
                      : null,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        report.reporterName,
                        style: const TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 14,
                        ),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        _formatDate(report.reportDate),
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                ),
                _buildRatingChip(report.rating),
              ],
            ),
          ),
          
          // 标题和位置
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  report.title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Icon(
                      Icons.location_on,
                      size: 16,
                      color: Colors.grey[600],
                    ),
                    const SizedBox(width: 4),
                    Expanded(
                      child: Text(
                        '${report.fishingSpotName} · ${report.location}',
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 14,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          // 钓获信息
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                _buildInfoChip(
                  Icons.catching_pokemon,
                  '${report.fishCount}条',
                  Colors.blue,
                ),
                const SizedBox(width: 8),
                _buildInfoChip(
                  Icons.scale,
                  '${report.totalWeight}kg',
                  Colors.green,
                ),
                const SizedBox(width: 8),
                _buildInfoChip(
                  Icons.access_time,
                  report.timeRange,
                  Colors.orange,
                ),
              ],
            ),
          ),

          // 鱼类标签
          if (report.fishTypes.isNotEmpty)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Wrap(
                spacing: 8,
                runSpacing: 4,
                children: report.fishTypes
                    .map((fishType) => Chip(
                          label: Text(
                            fishType,
                            style: const TextStyle(fontSize: 12),
                          ),
                          backgroundColor: Colors.blue[50],
                          labelStyle: TextStyle(color: Colors.blue[700]),
                          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        ))
                    .toList(),
              ),
            ),

          // 图片展示
          if (report.images.isNotEmpty)
            Container(
              height: 200,
              margin: const EdgeInsets.all(16),
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: report.images.length,
                itemBuilder: (context, index) {
                  return Container(
                    width: 150,
                    margin: const EdgeInsets.only(right: 8),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Image.network(
                        report.images[index],
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            color: Colors.grey[200],
                            child: const Icon(
                              Icons.image_not_supported,
                              color: Colors.grey,
                            ),
                          );
                        },
                      ),
                    ),
                  );
                },
              ),
            ),

          // 内容
          if (report.content.isNotEmpty)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Text(
                report.content,
                style: const TextStyle(
                  fontSize: 14,
                  height: 1.4,
                ),
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
              ),
            ),

          // 底部操作栏
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                _buildActionButton(
                  icon: report.isLiked ? Icons.thumb_up : Icons.thumb_up_outlined,
                  label: '${report.likeCount}',
                  color: report.isLiked ? Colors.blue : Colors.grey,
                  onTap: () {
                    context.read<FishingReportProvider>().toggleLike(report.id);
                  },
                ),
                const SizedBox(width: 16),
                _buildActionButton(
                  icon: Icons.comment_outlined,
                  label: '${report.commentCount}',
                  color: Colors.grey,
                  onTap: () {
                    // TODO: 跳转到评论页面
                  },
                ),
                const Spacer(),
                _buildDifficultyChip(report.difficulty),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatsTab() {
    return Consumer<FishingReportProvider>(
      builder: (context, provider, child) {
        if (provider.stats == null) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        final stats = provider.stats!;
        
        return SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 总体统计
              _buildStatsCard(
                title: '总体数据',
                children: [
                  _buildStatItem('总报告数', '${stats.totalReports}', Icons.assessment),
                  _buildStatItem('今日报告', '${stats.todayReports}', Icons.today),
                  _buildStatItem('平均评分', stats.averageRating.toStringAsFixed(1), Icons.star),
                  _buildStatItem('热门钓点', stats.mostPopularSpot, Icons.location_on),
                ],
              ),

              const SizedBox(height: 16),

              // 鱼类统计
              if (stats.fishTypeStats.isNotEmpty)
                _buildStatsCard(
                  title: '热门鱼类',
                  children: stats.fishTypeStats.entries
                      .take(5)
                      .map((entry) => _buildStatItem(
                            entry.key,
                            '${entry.value}次',
                            Icons.catching_pokemon,
                          ))
                      .toList(),
                ),

              const SizedBox(height: 16),

              // 钓点统计
              if (stats.spotStats.isNotEmpty)
                _buildStatsCard(
                  title: '热门钓点',
                  children: stats.spotStats.entries
                      .take(5)
                      .map((entry) => _buildStatItem(
                            entry.key,
                            '${entry.value}次',
                            Icons.pool,
                          ))
                      .toList(),
                ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildStatsCard({
    required String title,
    required List<Widget> children,
  }) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Text(
              title,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          const Divider(height: 1),
          ...children,
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Row(
        children: [
          Icon(icon, size: 20, color: Colors.blue[600]),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              label,
              style: const TextStyle(fontSize: 14),
            ),
          ),
          Text(
            value,
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRatingChip(double rating) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.amber[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.amber[200]!),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            Icons.star,
            size: 14,
            color: Colors.amber[600],
          ),
          const SizedBox(width: 4),
          Text(
            rating.toStringAsFixed(1),
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w600,
              color: Colors.amber[700],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoChip(IconData icon, String text, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: color),
          const SizedBox(width: 4),
          Text(
            text,
            style: TextStyle(
              fontSize: 12,
              color: color,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDifficultyChip(String difficulty) {
    Color color;
    switch (difficulty) {
      case '简单':
        color = Colors.green;
        break;
      case '中等':
        color = Colors.orange;
        break;
      case '困难':
        color = Colors.red;
        break;
      default:
        color = Colors.grey;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Text(
        difficulty,
        style: TextStyle(
          fontSize: 12,
          color: color,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required Color color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 18, color: color),
          const SizedBox(width: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 14,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  void _showFilterDialog() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _buildFilterSheet(),
    );
  }

  Widget _buildFilterSheet() {
    return Consumer<FishingReportProvider>(
      builder: (context, provider, child) {
        return Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 顶部拖拽条
              Container(
                margin: const EdgeInsets.only(top: 12),
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              
              // 标题
              Padding(
                padding: const EdgeInsets.all(16),
                child: Row(
                  children: [
                    const Text(
                      '筛选条件',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const Spacer(),
                    TextButton(
                      onPressed: () {
                        provider.clearFilters();
                        Navigator.pop(context);
                      },
                      child: const Text('清除'),
                    ),
                  ],
                ),
              ),

              // 筛选选项
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 位置筛选
                    const Text(
                      '钓点位置',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Wrap(
                      spacing: 8,
                      children: ['全部', '湖北省', '湖南省', '江西省', '安徽省']
                          .map((location) => FilterChip(
                                label: Text(location),
                                selected: provider.selectedLocation == 
                                    (location == '全部' ? null : location),
                                onSelected: (selected) {
                                  provider.setLocationFilter(
                                    location == '全部' ? null : location,
                                  );
                                },
                              ))
                          .toList(),
                    ),

                    const SizedBox(height: 16),

                    // 鱼类筛选
                    const Text(
                      '鱼类',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Wrap(
                      spacing: 8,
                      children: ['全部', '鲫鱼', '草鱼', '鲤鱼', '鲈鱼', '黑鱼']
                          .map((fishType) => FilterChip(
                                label: Text(fishType),
                                selected: provider.selectedFishType == 
                                    (fishType == '全部' ? null : fishType),
                                onSelected: (selected) {
                                  provider.setFishTypeFilter(
                                    fishType == '全部' ? null : fishType,
                                  );
                                },
                              ))
                          .toList(),
                    ),

                    const SizedBox(height: 16),

                    // 难度筛选
                    const Text(
                      '难度',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Wrap(
                      spacing: 8,
                      children: ['全部', '简单', '中等', '困难']
                          .map((difficulty) => FilterChip(
                                label: Text(difficulty),
                                selected: provider.selectedDifficulty == 
                                    (difficulty == '全部' ? null : difficulty),
                                onSelected: (selected) {
                                  provider.setDifficultyFilter(
                                    difficulty == '全部' ? null : difficulty,
                                  );
                                },
                              ))
                          .toList(),
                    ),

                    const SizedBox(height: 24),
                  ],
                ),
              ),

              // 确认按钮
              Padding(
                padding: const EdgeInsets.all(16),
                child: SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: const Text('确认'),
                  ),
                ),
              ),
              
              // 底部安全区域
              SizedBox(height: MediaQuery.of(context).padding.bottom),
            ],
          ),
        );
      },
    );
  }
}